package com.example.mytestdemo.hook

import android.app.Activity
import android.app.Instrumentation
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.util.Log
import com.example.mytestdemo.MainActivity
import com.example.mytestdemo.R
import java.lang.reflect.Field
import java.lang.reflect.Method


/**
 *@Author tgw
 *@Date 2023/04/19
 *@describe
 */
class MyInstrumentation(activityThread: Any,val mContext: Context) : Instrumentation() {
    private val mActivityThread: Any

    init {
        mActivityThread = activityThread
    }

    @Throws(
        InstantiationException::class,
        IllegalAccessException::class,
        ClassNotFoundException::class
    )
    override fun newActivity(
        cl: ClassLoader?,
        className: String?,
        intent: Intent?
    ): Activity {
        // 在这里进行启动时的 hook 操作
        Log.d("TAG", "newActivity: $className")
        if (className != null) {
            if (className.contains("SoftKeyActivity")) {
                val newIntent = Intent()
                newIntent.component = ComponentName(mContext, MainActivity::class.java)
                val activity = super.newActivity(cl, MainActivity::class.java.name, newIntent) as MainActivity
                // 设置自定义的主题
                activity?.setTheme(R.style.ActivitySplash1)
                return activity
            }

        }
        return super.newActivity(cl, className, intent)
    }


    companion object {
        fun attach(context: Context) {
            try {
                // 获取当前的 ActivityThread 对象
                val activityThreadClass = Class.forName("android.app.ActivityThread")
                val currentActivityThreadMethod: Method =
                    activityThreadClass.getMethod("currentActivityThread")
                val activityThread: Any = currentActivityThreadMethod.invoke(null)

                // 获取 Instrumentation 对象
                val instrumentationField: Field =
                    activityThreadClass.getDeclaredField("mInstrumentation")
                instrumentationField.setAccessible(true)
                val instrumentation: Instrumentation =
                    instrumentationField.get(activityThread) as Instrumentation

                // 创建自定义的 Instrumentation 对象并设置给 ActivityThread
                val myInstrumentation = MyInstrumentation(activityThread,context)
                instrumentationField.set(activityThread, myInstrumentation)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}



